import React, {Component, useEffect} from "react";

class Product extends Component {

  render() {
    const { products , asyncAddToCart} = this.props;
    return (<div>
      <h3>Products</h3>
      <ul>
        {products.map(item=>(
          <li key={item.id}>
            <p>{item.title}---{item.price}---{item.inventory}</p>

            <button
              disabled={!item.inventory}
              onClick={()=>asyncAddToCart(item)}> {!item.inventory?"sold out":"add to cart"} </button>
          </li>
          )
        )}
      </ul>
    </div>)
  }

  componentDidMount() {
    setTimeout(()=>{
      this.props.getAllProducts()
    },1000)
  }
}

// Product 等价 Product2
function Product2(props) {
  const { products, asyncAddToCart, getAllProducts} = props;
  
  useEffect(() => {
    getAllProducts()
  }, [])
  
  return (<div>
    <h1>Products</h1>
    <ul>
      {products.map(product => {
        return (<li key={product.id}>
          <p>{product.title} --- {product.price} --- {product.inventory}</p>
          <button 
            disabled={!product.inventory} 
            onClick={()=>asyncAddToCart(product)}
          >
            {!product.inventory ? 'sold out' : 'add to cart'}
          </button>
        </li>)
      })}
    </ul>
  </div>)
}

export default Product2